package com.wtgroup.demo.leetcode.q012_整数转罗马数字;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dafei
 * @version 0.1
 * @date 2021/3/27 15:27
 */
public class S_MyNumArrMap {

    public static void main(String[] args) {
        int[] inputs = {3, 4, 9, 58, 1994, 999, 3999};
        S_MyNumArrMap exe = new S_MyNumArrMap();
        for (int input : inputs) {
            System.out.println(exe.intToRoman(input));
        }
    }


    /**
     * 瞄了一眼题解开头, 自己蹦出的idea.
     * 数字和罗马字符的映射数组.
     * 目标数字取值, 减去, 剩下, 继续...
     */

    static String[] NUM_MAP = new String[1001];
    static Map<String, Integer> ROMAN_MAP = new HashMap<>();
    static {
        NUM_MAP[1] = "I";
        NUM_MAP[5] = "V";
        NUM_MAP[10] = "X";
        NUM_MAP[50] = "L";
        NUM_MAP[100] = "C";
        NUM_MAP[500] = "D";
        NUM_MAP[1000] = "M";
        // 小左大右情形
        NUM_MAP[4] = "IV";
        NUM_MAP[9] = "IX";
        NUM_MAP[40] = "XL";
        NUM_MAP[90] = "XC";
        NUM_MAP[400] = "CD";
        NUM_MAP[900] = "CM";
        // 剩下的补全: 自己知道下一个字符都填充为自己
        String prev = null;
        for (int i = 0; i < NUM_MAP.length; i++) {
            String cur = NUM_MAP[i];
            if (cur==null) {
                NUM_MAP[i] = prev;
            } else {
                prev = cur;
            }
        }

        // 字符->数字反向映射
        ROMAN_MAP.put("I", 1);
        ROMAN_MAP.put("V", 5);
        ROMAN_MAP.put("X", 10);
        ROMAN_MAP.put("L", 50);
        ROMAN_MAP.put("C", 100);
        ROMAN_MAP.put("D", 500);
        ROMAN_MAP.put("M", 1000);
        ROMAN_MAP.put("IV", 4);
        ROMAN_MAP.put("IX", 9);
        ROMAN_MAP.put("XL", 40);
        ROMAN_MAP.put("XC", 90);
        ROMAN_MAP.put("CD", 400);
        ROMAN_MAP.put("CM", 900);
    }


    public String intToRoman(int num) {
        String ans = "";
        int m = num / 1000;
        for (int i = 0; i < m; i++) {
            ans += "M";
        }
        int rest = num % 1000;
        while (rest > 0) {
            String roman = NUM_MAP[rest];
            ans += roman;
            rest -= ROMAN_MAP.get(roman);
        }

        return ans;
    }
}
